package com.taobaostore.web.controller.portal;

import java.util.Iterator;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.util.CollectionUtils;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import com.alipay.api.internal.util.AlipaySignature;
import com.alipay.demo.trade.config.Configs;
import com.google.common.collect.Maps;
import com.taobaostore.common.Const;
import com.taobaostore.common.ResponseCode;
import com.taobaostore.common.ServerResponse;
import com.taobaostore.pojo.User;
import com.taobaostore.service.IOrderService;
import com.taobaostore.vo.CartVo;
import com.taobaostore.vo.OrderVo;
import com.taobaostore.vo.ProductListVo;

@Controller
@RequestMapping("/order/")
public class OrderController {
	private static final Logger logger = LoggerFactory.getLogger(OrderController.class);
	
	@Autowired
	private IOrderService iOrderService;
	
	
	@RequestMapping("cancel.do")
	@ResponseBody
	public ServerResponse<String> cancelOrder(HttpSession session,Long orderOn){
		User user = (User)session.getAttribute(Const.CURRENT_USER);
		if (user==null) {
			return ServerResponse.createByError(ResponseCode.ILLEGAL_ARGUMENT.getCODE(), ResponseCode.ILLEGAL_ARGUMENT.getDESC());
		}
		return iOrderService.cancelOrder(user.getId(), orderOn);
	}
	
	
	
	
	@RequestMapping("list.do")
	@ResponseBody
	public ServerResponse<List<OrderVo>> listOrder(HttpSession session){
		User user = (User)session.getAttribute(Const.CURRENT_USER);
		if (user==null) {
			return ServerResponse.createByError(ResponseCode.ILLEGAL_ARGUMENT.getCODE(), ResponseCode.ILLEGAL_ARGUMENT.getDESC());
		}
		return iOrderService.getOrderVo(user.getId());
	}
	
	
	
	
	
	
	/**
	 * 新增订单
	 * @param session
	 * @param receiverId 收货地址
	 * @return
	 */
	@RequestMapping("create.do")
	@ResponseBody
	public ServerResponse create(HttpSession session,Integer receiverId) {
		User user = (User)session.getAttribute(Const.CURRENT_USER);
		if (user==null) {
			return ServerResponse.createByError(ResponseCode.ILLEGAL_ARGUMENT.getCODE(), ResponseCode.ILLEGAL_ARGUMENT.getDESC());
		}
		return iOrderService.create(user.getId(), receiverId);
	}

	
	
	/**
	 *   获取当前用户选中的商品记录
	 * @param session
	 * @param userId
	 * @return
	 */
	@RequestMapping("listCartProductVo.do")
	@ResponseBody
	public ServerResponse<CartVo> listCartProductVo(HttpSession session) {
		User user = (User)session.getAttribute(Const.CURRENT_USER);
		if (user==null) {
			return ServerResponse.createByError(ResponseCode.ILLEGAL_ARGUMENT.getCODE(), ResponseCode.ILLEGAL_ARGUMENT.getDESC());
		}
		return iOrderService.listCartProductVo(user.getId());
	}
	
	
	
	
	
	
	
	
	
	/***
	 * 生成支付宝付款二维码
	 * @param sessions
	 * @param orderId
	 * @param request
	 * @return
	 */
	@RequestMapping("pay.do")
	@ResponseBody
	public ServerResponse pay(HttpSession session,Long orderId,HttpServletRequest request){
		User user = (User)session.getAttribute(Const.CURRENT_USER);
		if (user==null) {
			return ServerResponse.createByError(ResponseCode.ILLEGAL_ARGUMENT.getCODE(), ResponseCode.ILLEGAL_ARGUMENT.getDESC());
		}
		return iOrderService.pay(orderId, user.getId(), "D://upload");
	}
	
	/**
	 * 支付宝支付回调函数
	 * @param request
	 * @return
	 */
	@RequestMapping("alipay_callback.do")
	@ResponseBody
	public Object alipayCallback(HttpServletRequest request) {
		System.out.println("===========================================================");
		System.out.println(request.getParameterMap().toString());
		System.out.println("===========================================================");
		Map<String, String> params = Maps.newHashMap();
		
		Map requestMap = request.getParameterMap();
		for(Iterator iter = requestMap.keySet().iterator();iter.hasNext();) {
			String name = (String)iter.next();
			String[] values = (String[]) requestMap.get(name);
			String valueStr = "";
			for (int i = 0; i < values.length; i++) {
				valueStr = (i == values.length - 1)?valueStr + values[i]:valueStr + values[i]+",";
			}
			params.put(name, valueStr);
			System.out.println("打印name");
			System.out.println(name);
			System.out.println("-----------------------");
		}
		logger.info("支付宝回调,sign:{},trade_status:{},参数{}",params.get("sign"),params.get("trade_status"),params.toString());
		// 验证回调的正确性,是不是支付宝发起的,避免重复通知
		params.remove("sign_type");
		try {
			boolean alipayRSACheckedV2 = AlipaySignature.rsaCheckV2(params, Configs.getAlipayPublicKey(), "utf-8",Configs.getSignType());
			if (!alipayRSACheckedV2) {
				return ServerResponse.createByError("非法请求,验证不通过!");
			}
		} catch (Exception e) {
		   logger.error("支付宝验证回调异常",e);
           e.printStackTrace();
		}
		// 验证各种数据
		ServerResponse serverResponse = iOrderService.aliCallback(params);
		if (serverResponse.isSuccess()) {
			System.out.println("支付宝回调完毕,前台工作都已经完成!");
			return Const.AlipayCallback.RESPONSE_SUCCESS;
		}
		return Const.AlipayCallback.RESPONSE_FAILED;
	}
	
	
	@RequestMapping("queryOrderPayStatus.do")
	@ResponseBody
	public ServerResponse<Boolean> queryOrderPayStatus(HttpSession session,Long orderNo) {
		User user = (User)session.getAttribute(Const.CURRENT_USER);
		if (user == null) {
			return ServerResponse.createByError(ResponseCode.NEED_LOGIN.getCODE(), ResponseCode.NEED_LOGIN.getDESC());
		}
		ServerResponse response = iOrderService.queryOrderPayStatus(user.getId(), orderNo);
		if (response.isSuccess()) {
			return ServerResponse.createBySuccess(true);
		}
		return ServerResponse.createBySuccess(false);
	}
	
}
